<script>
export default {
  name: 'SlUpload',
  props: {
    value: {
      type: Array
    }
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: []
    }
  },
  methods: {
    handleRemove(file, fileList) {
      this.fileList = fileList
      this.$emit('input', this.fileList)
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },

    onExceed() {
      this.$message.warning('只能上传两张图片')
    },

    beforeUpload(file) {
      const isImg = file.type.startsWith('image')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImg) this.$message.error('只能上传图片!')
      if (!isLt2M) this.$message.error('上传图片大小不能超过2MB!')
      return isImg && isLt2M
    },

    async httpRequest({ file }) {
      const formData = new FormData()
      formData.append('file', file)
      try {
        const item = await this.$store.dispatch('commonStore/uploadImageAction', formData)
        this.fileList.push(item)
        this.$emit('input', this.fileList)
        this.$message.success('图片上传成功')
      } catch (error) {
        this.$message.error(error.message)
      }
    }

  }

}
</script>

<template>
  <div class="upload">
    <div class="upload-container">
      <div class="the-main" v-if="!value.length">
        <img src="@/assets/theMain.png" class="left">
      </div>
      <div class="vice" v-if="!value.length">
        <img src="@/assets/vice.png" class="right"/>
      </div>
      <el-upload action="#" list-type="picture-card" :limit="2" :file-list="value" :on-exceed="onExceed" :http-request="httpRequest" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :before-upload="beforeUpload">
        <i class="el-icon-plus"></i>
        <template #tip>
          <p class="tip">注：图片大小不超过5M；仅能上传 PNG JPEG JPG类型图片；建议上传400*300尺寸的图片；最多上传2张</p>
        </template>
      </el-upload>
    </div>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl">
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
::v-deep .el-upload {
  width: 250px;
  height: 150px;
  line-height: 150px;
}

.upload-container {
  display: flex;

  .the-main, .vice {
    width: 250px;
    height: 150px;
    border: 1px solid #ccc;

  }

  .vice {
    margin: 0 10px;
  }

  .tip {
    font-size: 12px;
    color: #cccccc;
  }
}

::v-deep .el-upload-list__item-actions {
  width: 250px;
  height: 150px;
}

::v-deep .el-upload-list__item-thumbnail {
  width: 250px;
  height: 150px;
}

::v-deep .el-upload-list__item.is-ready {
  width: 250px;
  height: 150px;
}

::v-deep .el-upload-list__item.is-success {
  width: 250px;
  height: 150px;
}

img {
  width: 100%;
  height: 100%;
}

</style>
